<template>
  <!-- 系统设置模块-自动分配设置页面 -->
  <div class="fillcontain bgfff">
    <!-- 标题 -->
    <div class="fastQuery bgfff">
      <el-row>
        <el-col :span="6" class="fastQuery_title">
          <i class="el-icon-tickets"></i><span> 自动分配设置</span></el-col>
        <el-col :span="8"></el-col>
      </el-row>
    </div>
    <!-- 表单 -->
    <el-form ref="ruleInfoForm"
             :rules="cycleInfoRules"
             :model="cycleInfo"
             label-width="140px"
             class="form_container bgfff">
      <el-row>
        <el-col :span="8">
          <el-form-item label="核保池大小(单)" prop="poolLimit">
            <el-input-number clearable v-model="cycleInfo.poolLimit" :min="1" :max="300"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label-width="180px" label="照会任务池大小(单)" prop="zhPoolLimit">
            <el-input-number clearable v-model="cycleInfo.zhPoolLimit" :min="1" :max="300"></el-input-number>
          </el-form-item>
        </el-col>
        <!--<el-col :span="8">
          <el-form-item label="自动分配周期(分钟)" prop="cycle">
            <el-input v-model="cycleInfo.cycle" placeholder="自动分配周期"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="每天执行时间(开始)" prop="startTime">
            <el-date-picker
                type="date"
                v-model="cycleInfo.startTime"
                value-format="yyyy-MM-dd"
                :picker-options="{}"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="每天执行时间(结束)" prop="endTime">
            <el-date-picker
                type="date"
                v-model="cycleInfo.endTime"
                value-format="yyyy-MM-dd"
                :picker-options="{}"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>-->
      </el-row>
    </el-form>
    <div class="contain autoSettings">
      <div class="check_contain">
        <div class="fastQuery">
          <el-row>
            <el-col :span="6" class="fastQuery_title">
              <i class="el-icon-tickets"></i><span> 分配开启/关闭</span></el-col>
            <el-col :span="8"></el-col>
          </el-row>
        </div>
        <el-row class="checkList">
          <el-col :span="24">
            <el-switch
                    v-model="onOrOff"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-text="开启"
                    inactive-text="关闭">
            </el-switch>
          </el-col>
        </el-row>
      </div>
      <div class="check_contain">
        <div class="fastQuery">
          <el-row>
            <el-col :span="6" class="fastQuery_title">
              <i class="el-icon-tickets"></i><span> 核保员筛选规则</span></el-col>
            <el-col :span="8"></el-col>
          </el-row>
        </div>
        <el-row class="checkList">
          <el-col :span="24">
            <el-checkbox v-model="cycleInfo.onlineStatus">是否在线</el-checkbox>
            <el-checkbox v-model="cycleInfo.poolStatus">工作池未满</el-checkbox>
          </el-col>
        </el-row>
      </div>
      <div class="check_contain">
        <div class="fastQuery">
          <el-row>
            <el-col :span="6" class="fastQuery_title">
              <i class="el-icon-tickets"></i><span> 分配客户/任务</span></el-col>
            <el-col :span="8"></el-col>
          </el-row>
        </div>
        <el-row class="checkList">
          <el-col :span="24">
            <el-radio-group v-model="cycleInfo.operType">
              <el-radio label="1">分配客户</el-radio>
              <el-radio label="2">分配任务</el-radio>
            </el-radio-group>
          </el-col>
        </el-row>
      </div>
      <div class="table_container check_contain">
        <div class="fastQuery">
          <el-row>
            <el-col :span="6" class="fastQuery_title">
              <i class="el-icon-tickets"></i><span> 任务分配规则</span></el-col>
            <el-col :span="8"></el-col>
          </el-row>
        </div>
        <el-table
            v-loading="loading"
            :data="cycleRelations"
            :default-sort="{prop: 'ruleOrder', order: 'ascending'}"
            highlight-current-row
            header-cell-class-name="table-header-class"
            style="width:100%"
            class="mt10">
          <el-table-column
              property="ruleContent"
              label="规则描述"
              align='center'>
          </el-table-column>
          <el-table-column
              property="ruleStatus"
              label="是否有效"
              align='center'>
            <template slot-scope="scope">
              <el-switch
                  v-model="scope.row.ruleStatus"
                  active-value="1"
                  inactive-value="0">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
              property="ruleUser"
              label="指定人员"
              align='center'>
            <template slot-scope="scope">
              <el-input clearable v-model="scope.row.ruleUser" placeholder="指定人员"></el-input>
            </template>
          </el-table-column>
          <el-table-column
              property="ruleOrder"
              fixed="right"
              label="排序"
              align='center'>
            <template slot-scope="scope">
              <span class="operationIcon ml10" @click="doUpOne(scope.row)">
                <!-- 排序图标按钮 -->
                <i class="el-icon-top"></i>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-row class="pb20 pt20 bor_top mt20">
      <el-col :span="12" class="text_right pr20">
        <el-button type="danger" @click="doValid('ruleInfoForm', false)">试运行</el-button>
      </el-col>
      <el-col :span="12">
        <el-button type="danger" @click="doValid('ruleInfoForm', true)" class="Defaultbutton">发布
        </el-button>
      </el-col>
    </el-row>
    <!-- 试运行弹窗 -->
    <el-dialog title="试运行" :visible.sync="dialogFormVisible" width="50%" center>
      <el-table
          :data="distributionResults"
          :default-sort="{prop: 'distributionUserId', order: 'ascending'}"
          :max-height="500"
          highlight-current-row
          header-cell-class-name="table-header-class"
          style="width:100%"
          class="mt10">
        <el-table-column
            property="distributionUserId"
            label="核保员ID"
            align='center'>
        </el-table-column>
        <el-table-column
            property="caseno"
            label="受理号"
            align='center'>
        </el-table-column>
        <el-table-column
            property="chdrnum"
            label="保单号"
            align='center'>
        </el-table-column>
        <el-table-column
            property="busitype"
            label="业务类型"
            align='center'>
          <template slot-scope="scope">
            <span v-for="item in busiTypes"
                  v-if="item.value == scope.row.busitype">{{item.label}}</span>
          </template>
        </el-table-column>
        <el-table-column
            property="routeid"
            label="节点名称"
            align='center'>
          <template slot-scope="scope">
            {{allRouteidAndName[scope.row.routeid]}}
          </template>
        </el-table-column>
        <el-table-column
                property="routeid"
                label="备注"
                align='center'>
          <template slot-scope="scope">
            {{scope.row.remark}}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">返 回</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {doRuleTest, doRuleUpdate, getRuleInfo,getBatchOnOrOff} from "@/api/setting";
  import constant from "@/utils/constant";
  import sessionStorageUtil from "@/utils/sessionStorageUtil";

  export default {
    data() {
      return {
        dialogFormVisible: false,
        // 自动分配规则定义表
        cycleInfoRules: {
          poolLimit: [
            {required: true, message: '请输入核保池大小！', trigger: 'change'}
          ],
          cycle: [],
          startTime: [],
          endTime: [],
          operUserRule: [],
          operType: [],
          zhPoolLimit: [
            {required: true, message: '请输入照会任务池大小！', trigger: 'change'}
          ]
        },
        cycleInfo: {
          id: '',              // id
          status: '',          // 状态
          createId: '',        // 创建人ID
          createTime: '',      // 创建时间
          lastUpdateId: '',    // 更新人ID
          lastUpdateTime: '',  // 更新时间
          poolLimit: '',       // 每人任务池大小（单）
          cycle: '',           // 自动分配周期（分钟）
          startTime: '',       // 每天执行时间（起始）
          endTime: '',         // 每天执行时间（结束）
          operUserRule: '',    // 不分配核保员ID列表字符串“，”逗号隔开
          operType: '',        // 分配客户/任务
          zhPoolLimit: '',     // 照会任务池大小（单）
          onlineStatus: '',    // 核保员规则：是否登录
          poolStatus: '',      // 核保员规则：工作池未满
        },
        onOrOff:false, //开启/关闭 默认关闭
        // 规则列表
        cycleRelations: [],
        // 试运行分配结果
        distributionResults: [],
        busiTypes: constant.busiTypes,
        allRouteidAndName: {},
        loading: false,
      }
    },
    created() {
      this.getInfo();
      this.allRouteidAndName = sessionStorageUtil.getRouteidAndNameList();
    },
    mounted() {
    },
    methods: {
      // 初始化查询信息
      getInfo() {
        getRuleInfo().then(res => {
          if (res.resultCode == constant.SUCCESS && res.data) {
            this.cycleInfo = res.data.cycleInfo;
            this.cycleInfo.onlineStatus = this.cycleInfo.onlineStatus == 0 ? true : false;
            this.cycleInfo.poolStatus = this.cycleInfo.poolStatus == 0 ? true : false;
            // 根据升序排序
            res.data.cycleRelations.sort((a, b) => a.ruleOrder - b.ruleOrder);
            this.cycleRelations = res.data.cycleRelations;
          }
        });
        getBatchOnOrOff().then(res => {
          if (res.resultCode == constant.SUCCESS && res.data) {
            if (res.data.length > 0 && res.data[0].sddValue1 == 'Y') {
              this.onOrOff = true
            }
          }
        });
      },
      // 点击发布
      doPublish() {
        let cycleInfo = {};
        for (let key in this.cycleInfo) {
          if (key == 'onlineStatus' || key == 'poolStatus') {
            cycleInfo[key] = this.cycleInfo[key] ? 0 : 1;
          } else {
            cycleInfo[key] = this.cycleInfo[key];
          }
        }
        const params = {
          cycleInfo: cycleInfo,
          cycleRelations: this.cycleRelations,
          onOrOff:this.onOrOff
        };
        doRuleUpdate(params).then(res => {
          if (res.resultCode == constant.SUCCESS) {
            this.$message({
              type: 'success',
              message: '发布成功！'
            });
          }
        });
      },
      // 点击试运行
      doTest() {
        let cycleInfo = {};
        for (let key in this.cycleInfo) {
          if (key == 'onlineStatus' || key == 'poolStatus') {
            cycleInfo[key] = this.cycleInfo[key] ? 0 : 1;
          } else {
            cycleInfo[key] = this.cycleInfo[key];
          }
        }
        const params = {
          taskOperCycle: cycleInfo,
          taskOperRelations: this.cycleRelations.filter((item) => {return item.ruleStatus == "1";})
        };
        doRuleTest(params).then(res => {
          if (res.resultCode == constant.SUCCESS) {
            if (res.data && res.data.length > 0) {
              this.distributionResults = res.data;
              this.dialogFormVisible = true;
            } else {
              this.$message({
                type: 'warning',
                message: res.resultMsg || '无任务分配'
              });
            }
          }
        });
      },
      doValid(formName, isPublish) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (isPublish) {
              this.doPublish();
            } else {
              this.doTest();
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 排序向上移动一位
      doUpOne(oneItem) {
        const currentIndex = (this.cycleRelations || []).findIndex((item) => item.code === oneItem.code);
        if (currentIndex === 0) {
          this.$message({
            type: 'warning',
            message: '请注意，该分配规则已排在最前！'
          });
          return false;
        }
        const ruleOrderB = this.cycleRelations[currentIndex - 1].ruleOrder;
        const ruleOrderA = this.cycleRelations[currentIndex].ruleOrder;
        this.cycleRelations[currentIndex - 1].ruleOrder = ruleOrderA;
        this.cycleRelations[currentIndex].ruleOrder = ruleOrderB;
        // 根据升序排序
        this.cycleRelations.sort((a, b) => a.ruleOrder - b.ruleOrder);
      }
    },
    computed: {}
  }
</script>
<style lang="less" scoped>
  .fillcontain {
    padding-bottom: 0;

    .fastQuery {
      padding: 15px 20px 10px 20px;
      border-bottom: 1px solid #e1e1e1;

      .fastQuery_title {
        color: #666;
        padding: 6px 0px;
      }
    }

    .form_container {
      padding: 20px 0 10px 0;
      margin: 0 auto;
      width: 70%;
    }
  }

  .contain {
    background: #fff;
    padding: 10px;
    margin-bottom: 20px;

    .check_contain {
      .fastQuery_title {
        color: #333;
        font-weight: bold;
      }

      .checkList {
        padding: 15px 20px 15px 60px;
      }

    }
  }

  .autoSettings {
    background-color: #f9f9f9 !important;
    width: 70%;
    margin: 0 auto;
    padding: 0 20px !important;
  }

  .operationIcon {
    // padding: 12px;
    border: 1px solid #e5e5e5;
    border-radius: 50%;
    width: 22px;
    height: 22px;
    display: inline-block;
    cursor: pointer;
    box-shadow: 0 0 3px #f9f9f9;

    .el-icon-top {
      color: #68a3fc !important;
    }
  }

  // 默认按钮 实心红色按钮
  .Defaultbutton {
    background-color: #f76767 !important;
    color: #fff !important;
  }

  .Defaultbutton:hover {
    background-color: #f78989 !important;
    color: #fff !important;
  }
</style>
